package mywebapps.security.dao.hibernate;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;

import mywebapps.common.utils.HibernateUtil;
import mywebapps.security.dao.RoleDao;
import mywebapps.security.model.Role;

public class RoleDaoImpl implements RoleDao
{

    @SuppressWarnings("unchecked")
    @Override
    public List<Role> getAllRoles()
    {
        SessionFactory factory = HibernateUtil.getInstance().getSessionFactory();
        Session session = factory.getCurrentSession();
        session.beginTransaction();
        Query query = session.getNamedQuery("Role.findAllRoles");
        
        List<Role> roles = (List<Role>) query.list();
        
        session.getTransaction().commit();
        return roles;
    }

    @Override
    public Role getRole(int roleId)
    {
        SessionFactory factory = HibernateUtil.getInstance().getSessionFactory();
        Session session = factory.getCurrentSession();
        session.beginTransaction();
        Query query = session.getNamedQuery("Role.findRoleById");
        query.setInteger("roleId", roleId);
        
        Role role = (Role) query.uniqueResult();
        
        session.getTransaction().commit();
        return role;
    }

    @Override
    public void createRole(Role role)
    {
        SessionFactory factory = HibernateUtil.getInstance().getSessionFactory();
        Session session = factory.getCurrentSession();
        session.beginTransaction();
        role.setLastUpdateUser("BILLIBWEBAPP");
        session.save(role);
        session.getTransaction().commit();
    }

    @Override
    public void updateRole(Role role)
    {
        SessionFactory factory = HibernateUtil.getInstance().getSessionFactory();
        Session session = factory.getCurrentSession();
        session.beginTransaction();
        session.update(role);
        session.getTransaction().commit();
    }

    @Override
    public void deleteRole(Role role)
    {
        SessionFactory factory = HibernateUtil.getInstance().getSessionFactory();
        Session session = factory.getCurrentSession();
        session.beginTransaction();
        session.delete(role);
        session.getTransaction().commit();
    }
}
